<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-19 15:02:14
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\basic\uiTable\uiTable.vue
 * CIMC-V2
-->

<template>
  <div
    :id="'uiTable-body-' + info._id"
    ref="uiTable-body"
    class="ui-tabel relative"
    :class="[hasMini ? 'table-mini' : '', info.extension.customStyle && info.extension.customStyle.value ? 'cunstomTableStyle' : '']"
  >
    <div
      v-show="!(info.extension.removeTopBar && info.extension.removeTopBar.value)"
      :ref="info._id + '_buttonBox'"
      class="ui-flexbox min-h-[22px]"
      :style="{
        width: 'calc(100% - 80px)',
      }"
    >
      <Widget v-if="!hasPreview" class="flex flex-wrap" :list="info.list" />
      <div
        v-else
        class="flex flex-wrap relative draggable-canvas preview-canvas"
        :class="info.extension.maxHeight && info.extension.maxHeight.value ? '' : 'h-full'"
      >
        <div v-for="element in showButtonList" :key="element._id" class="component-box relative" :class="[element.type]" :data-com-id="element._id">
          <component :is="element.type" :info="element">
            <slot></slot>
          </component>
        </div>
        <el-dropdown v-if="foldButtonList.length" popper-class="table-botton-box-popper" trigger="hover">
          <el-button circle>
            <vui-icon icon="more-line" />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in foldButtonList" :key="item._id" class="flex justify-center" :style="{ marginBottom: '3px' }">
                <component :is="item.type" :info="item">
                  <slot></slot>
                </component>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <vxe-grid
      :ref="info._id"
      v-ui-ref="vSetRef"
      v-bind="gridOptions"
      :cell-style="cellStyle"
      :class="{ noScrollBar: info.extension.noScrollBar && info.extension.noScrollBar.value }"
      :max-height="info.extension.maxHeight && info.extension.maxHeight.value"
      :row-class-name="info.extension.rowHeight && info.extension.rowHeight.value"
      :row-style="rowStyle"
      :scroll-x="scrollXConfig"
      :scroll-y="{ gt: 50 }"
      :style="{
        'background-color': (info.extension.BgColor && info.extension.BgColor.value) || 'initial',
        color: (info.extension.textColor && info.extension.textColor.value) || 'initial',
        'border-color': (info.extension.borderColor && info.extension.borderColor.value) || 'initial',
        'background-image': (info.extension.borderColor && info.extension.borderColor.value) || 'initial',
      }"
      @cell-click="cellClickEvent"
      @cell-dblclick="cellDBLClickEvent"
      @cell-menu="cellMenuEvent"
      @checkbox-change="checkboxChange"
      @edit-actived="editActivedEvent"
      @keydown="handlerKeyDown"
      @menu-click="contextMenuClickEvent"
      @page-change="pageChange"
      @radio-change="radioChange"
      @sort-change="sortChange"
      @toggle-row-expand="toggleRowExpand"
    >
      <!-- 工具栏 -->
      <template #toolbar_tools>
        <vxe-button
          v-if="columnEditConfig.open && !columnEditModule"
          class="refresh-btn"
          size="mini"
          :style="{ width: '30px' }"
          title="进入编辑模式"
          @click="intoColumnEditModel"
        >
          <!-- <vui-icon icon="edit-line" /> -->
          编辑
        </vxe-button>
        <vxe-button
          v-else-if="columnEditConfig.open && columnEditModule"
          class="refresh-btn"
          size="mini"
          :style="{ width: '30px' }"
          title="退出编辑模式"
          @click="saveColumnEdit"
        >
          <!-- <vui-icon icon="close-circle-line" /> -->
          保存
        </vxe-button>
        <div :style="{ position: 'absolute', top: '22px', right: '0px', zIndex: 9 }">
          <vxe-button v-if="info.extension.toolBar ? info.extension.toolBar.value : true" class="refresh-btn in-table" size="mini" @click="onRefresh">
            <vui-icon :class="{ roll: hasClickRefreshLoading }" icon="refresh-line" />
          </vxe-button>
          <div v-if="isShowCustom && (info.extension.toolBar ? info.extension.toolBar.value : true)">
            <vxe-button class="refresh-btn in-table" size="mini" @click="showCustomOption = !showCustomOption">
              <vui-icon icon="list-settings-line" />
            </vxe-button>
            <CustomOption :active="showCustomOption" :columns="getTableColumns" :table-id="info._id" @saveToTable="saveToTable" />
          </div>
        </div>
      </template>
      <template #[v.field]="{ row, rowIndex }" v-for="(v, index) in switchSlots" :key="index">
        <el-switch
          v-model="row[v.field]"
          :active-value="v.formItemType.active"
          :inactive-value="v.formItemType.inactive"
          @change="tableSwitch(row, rowIndex, v)"
        />
      </template>
      <template #[v.field]="{ row, rowIndex }" v-for="(v, index) in selectSlots" :key="index">
        <el-select
          :ref="`${row._X_ROW_KEY}-${v.field}`"
          v-model="row[v.field]"
          default-first-option
          filterable
          placeholder="请选择"
          size="mini"
          @change="tableSwitch(row, rowIndex, v)"
        >
          <el-option
            v-for="item in v.options"
            :key="item[v.formItemType.valueField]"
            :label="item[v.formItemType.labelField]"
            size="mini"
            :value="item[v.formItemType.valueField]"
          />
        </el-select>
      </template>
      <template #[v.field]="{ row, rowIndex }" v-for="(v, index) in inputSlots" :key="index">
        <el-input :ref="`${row._X_ROW_KEY}-${v.field}`" v-model="row[v.field]" size="mini" @change="tableSwitch(row, rowIndex, v)" />
      </template>
      <template #[`columnEdit_${v.field}`]="{ row }" v-for="(v, index) in columnEditSlots" :key="index">
        <el-input v-model="row[v.field]" :class="['tableColumnEdit', `rowId-${row._X_ROW_KEY}-${v.field}`]" size="mini" @dblclick.stop="" />
      </template>
      <!-- 多选头 -->
      <template #checkbox_header="{ checked, indeterminate }">
        <div class="flex cursor-pointer">
          <span class="custom-checkbox" @click.stop="checkboxSelectAll">
            <template v-if="indeterminate">
              <i class="ri-checkbox-indeterminate-line text-blue-500"></i>
            </template>
            <template v-else-if="checked">
              <i class="ri-checkbox-fill text-blue-500"></i>
            </template>
            <template v-else>
              <i class="ri-checkbox-blank-line text-gray-300"></i>
            </template>
          </span>
          <!-- <span @click="checkboxSelectAll">{{ column.title }}</span> -->
          <span>/</span>
          <span @click="checkboxReverseSelection">{{ translateTitle(`Ve.elements.table.反选`) }}</span>
        </div>
      </template>

      <!-- 编辑模式 -->
      <template v-for="(v, index) in editSlots" :key="index" #[v.field]="{ row }">
        <!-- <vxe-input v-model="row[v]" placeholder="请输入" type="text" @change="getTableRef().updateStatus({ row, column })" /> -->
        <div class="flex items-center py-1">
          <UiTableInput
            v-if="!v.formItemType.type"
            :form-data-key="v.field"
            :form-data-value="row[v.field]"
            @dblclick.stop=""
            @editNextRow="editNextRow"
            @formDataItemChange="
              (newVal) => {
                formDataItemChange(row, newVal)
              }
            "
          />
          <component
            :is="v.formItemType.type"
            v-else
            :disabled="(isAddTableEdit && v.formItemType.addDesabled) || (!isAddTableEdit && v.formItemType.editDesabled)"
            :edit-form-item="editFormItem"
            :form-data-key="v.formItemType.model || v.field"
            :form-data-label="v.field"
            :form-data-value="row[v.formItemType.model || v.field]"
            :info="v.formItemType.info"
            :row-data="row"
            :table-ref="$refs[info._id]"
            @click.stop=""
            @dblclick.stop=""
            @editFormItemChange="editFormItemChange"
            @editNextRow="editNextRow"
            @formDataItemChange="
              (newVal) => {
                formDataItemChange(row, newVal)
              }
            "
          />
          <vui-icon
            v-if="info.extension.openRevertData && info.extension.openRevertData.value"
            class="ml-2"
            icon="arrow-go-back-line"
            :style="{ fontSize: '14px', cursor: 'pointer' }"
            title="撤销"
            @click="revertData(row, v.field, v.formItemType.model)"
          />
        </div>
      </template>

      <!-- 空数据 -->
      <template #empty>
        <el-empty :description="translateTitle('Ve.elements.table.暂无数据')" />
      </template>

      <!-- 展开行 -->
      <template #expand_row_slot="{ row }">
        <div :style="{ padding: '30px' }">
          <vxe-grid
            :align="info.extension.align && info.extension.align.value"
            auto-resize
            border
            class="expandTable"
            :column-config="{
              useKey: true,
              resizable: true,
            }"
            :columns="getExpandTableColumns"
            :data="expandData[row._X_ROW_KEY]"
            max-height="200"
            resizable
            :row-config="{
              useKey: true,
              isHover: true,
              isCurrent: true,
            }"
            show-header-overflow
            show-overflow
          >
            <!-- 空数据 -->
            <template #empty>
              <el-empty :description="translateTitle('Ve.elements.table.暂无数据')" />
            </template>
          </vxe-grid>
        </div>
      </template>

      <!-- 展开列头 -->
      <template #expand_col_header>
        <el-button v-show="!expandCount || !getExpandAll" :style="{ margin: 0, padding: 0 }" type="text" @click="expandAll(true)">
          {{ translateTitle('Ve.elements.table.全部展开') }}
        </el-button>
        <el-button v-show="getExpandAll" :style="{ margin: 0, padding: 0 }" type="text" @click="expandAll(false)">
          {{ translateTitle('Ve.elements.table.全部折叠') }}
        </el-button>
      </template>

      <!-- 自定义单元格渲染 -->
      <template #custom_cell_slot="{ row, column }">
        <vui-icon
          v-if="cellCustomStyle[`${column.field}_${row[column.field]}`] && cellCustomStyle[`${column.field}_${row[column.field]}`].icon"
          :icon="cellCustomStyle[`${column.field}_${row[column.field]}`].icon"
          :style="{ color: cellCustomStyle[`${column.field}_${row[column.field]}`].iconColor }"
        />
        <el-tag
          v-if="cellCustomStyle[`${column.field}_${row[column.field]}`] && cellCustomStyle[`${column.field}_${row[column.field]}`].tagContent"
          :type="cellCustomStyle[`${column.field}_${row[column.field]}`].tagType"
        />
        <span>{{ row[column.field] }}</span>
      </template>
    </vxe-grid>
  </div>
</template>
<script>
  import request from '@/utils/request'
  import isEmpty from 'lodash/isEmpty'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'
  import { GFCD } from '@/utils/utils'

  import Sortable from 'sortablejs'
  import { defineComponent, defineAsyncComponent } from 'vue'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import { actionsTask } from '@ve/eventTask/index'
  import cloneDeep from 'lodash/cloneDeep'
  import isFunction from 'lodash/isFunction'
  import { domHeight } from '@ve/utils/domHeight'
  import { replaseRegVariable, processingConstant, findListItem } from '@ve/utils/utils'
  import UiTableInput from './uiTableFormItem/uiTableInput'
  import UiTableSelect from './uiTableFormItem/uiTableSelect'
  import UiTableNumberInput from './uiTableFormItem/uiTableNumberInput'
  import UiTableSwitch from './uiTableFormItem/uiTableSwitch'
  import UiTableDate from './uiTableFormItem/uiTableDate'
  import UiButton from '@ve/elements/form/uiButton/uiButton'
  import UiTolead from '@ve/elements/form/uiTolead/uiTolead'
  import UiDownload from '@ve/elements/form/uiDownload/uiDownload'
  import UiDropdown from '@ve/elements/form/uiDropdown/uiDropdown'
  import uiUpload from '@ve/elements/form/uiUpload/uiUpload'
  import UiPrint from '@ve/elements/basic/uiPrint/uiPrint'
  import { translateTitle } from '@/utils/i18n'
  //表头自定义显示保存
  import CustomOption from './customOption'

  const meanNum = (list, field) => {
    let count = 0
    list.forEach((item) => {
      count += Number(item[field])
    })
    return count <= 0 || list.length <= 0 ? 0 : (count / list.length).toFixed(2)
  }
  const sumNum = (list, field) => {
    let count = 0
    list.forEach((item) => {
      count += Number(item[field])
    })
    return count.toFixed(2)
  }
  export default defineComponent({
    name: 'UiTable',
    components: {
      Widget: defineAsyncComponent(() => import('@ve/components/widget.vue')),
      UiTableInput,
      UiTableSelect,
      UiTableNumberInput,
      UiTableSwitch,
      UiTableDate,
      UiButton,
      UiTolead,
      UiDownload,
      CustomOption,
      UiDropdown,
      UiPrint,
      uiUpload,
    },
    mixins: [UiMixin, RefsInjectMixin],
    emits: ['outSelected'],
    data() {
      return {
        showCustomOption: false,

        dataSourceChangeIndex: 0,
        columnSortable: null,
        pageSize: 1,
        tabelHeight: 300,
        list: [],
        loading: false,
        //click记录
        clickRowId: '', //点击行id 单击双击
        hasClickRefreshLoading: false,
        cacheFormData: {}, //缓存formdata
        hasCheckboxSelectAll: false, //是否全选
        selectRow: {}, //选中数据行
        //可编辑slots数据
        editSlots: [],
        switchSlots: [],
        selectSlots: [],
        inputSlots: [],
        hasOpenEdit: false,
        // editActivedVisible: false,
        //操作按钮
        //排序状态
        sortType: {},
        //批次属性表头
        batchAttributeColumns: [],
        dataSourceFormData: {}, // 数据源绑定获取的数据（不作为参数使用时）
        hasMini: false,
        //缓存编辑模式下的数据
        cacheEditRows: {},
        editFormItem: '', // 当前触发改变的表单项
        scrollXConfig: {
          gt: 10,
          enabled: true,
        },
        editModel: false, // 是否为编辑模式
        buttonIsOverflowing: false, // 按钮是否溢出
        showButtonList: [], // 未折叠的按钮组
        foldButtonList: [], // 折叠的按钮组
        buttonWidthObj: {},
        //表格是否显示自定义排序 动态表格不需要显示
        isShowCustom: true,
        disposeButtonTimeOut: null,
        menuClickIsRunning: false, // 右键菜单事件是否进行中
        columnEditModule: false, // 是否是列编辑模式
        columnEditConfig: {}, // 列编辑模式配置
        columnEditSlots: [],
        isAddTableEdit: false, // 是否是新增表格数据进入的编辑模式
        isNotSaveData: false, // 是否不自动保存编辑数据，用于esc退出编辑模式
        // 新增表格数据动作数据
        addTableDataEventObj: {
          saveApiConfig: {}, // 新增表格数据的保存接口
          vm: {},
          eventName: '',
          done: null,
          eventObj: {},
        },
        expandData: {}, // 展开行的数据
        customColData: {}, // 自定义单元格渲染配置数据（图标 tag 等）
        cellCustomStyle: {}, // 自定义单元格样式
        expandCount: 0, // 表格展开行展开的数量
        keepSelectData: [], // 缓存选中数据，用作刷新后选中数据
      }
    },
    computed: {
      currentPage() {
        return this.info.data.formData['#LIMIT#']
      },
      getCount() {
        return this.info.data.requestData?.count || 0
      },
      getData() {
        return this.info.data.requestData?.data || []
      },
      gridOptions() {
        let gridOptionsData = {
          rowConfig: {
            useKey: true,
            isHover: true,
            isCurrent: true,
          },
          columnConfig: {
            useKey: true,
            resizable: true,
          },
          showHeaderOverflow: true,
          keepSource: true,
          columnKey: true,
          stripe: true,
          loading: this.loading,
          resizable: true,
          autoResize: true,
          border: true,
          showOverflow: true,
          height: this.tabelHeight, //'auto',
          radioConfig: { highlight: true },
          checkboxConfig: { highlight: true },
          pagerConfig: {
            enabled: this.info.extension.pagerEnabled && this.info.extension.pagerEnabled.value && true,
            size: 'mini',
            pageSizes: this.info.extension.pageSizes.value.map((v) => Number(v)),
            pageSize: this.pageSize,
            total: this.getCount || 0,
            currentPage: this.currentPage,
          },
          // data: this.list || [],
          columns: this.getTableColumns,
          toolbarConfig: {
            slots: {
              tools: 'toolbar_tools',
            },
            className: 'vui-toolbar-box',
            // custom: {
            //   trigger: 'click',
            // },
            custom: false,
          },
        }
        //底部合计
        if (this.info.extension.footerMethodConfig) {
          gridOptionsData.showFooter = this.info.extension.footerMethodConfig.value.open
          gridOptionsData.footerMethod = ({ columns, data }) => {
            let arr = []
            this.info.extension.footerMethodConfig.value.data.forEach((row) => {
              arr.push(
                columns.map((column, columnIndex) => {
                  if (columnIndex === 0) {
                    return this.info.extension.footerMethodConfig.value.options.find((el) => el.value == row.value).label
                  }
                  if (row.key.includes(column.property)) {
                    return row.value == '1' ? sumNum(data, column.property) : meanNum(data, column.property)
                  }
                  return ''
                })
              )
            })
            return arr
          }
        }
        if (this.info.extension.menuConfig) {
          let _menuConfig = this.info.extension.menuConfig.value
          _menuConfig.forEach((v) => {
            if (v.extension && v.extension.icon) {
              v.prefixIcon = `ri-${v.extension.icon.value}`
            }
          })
          gridOptionsData.menuConfig = {
            className: this.menuClickIsRunning ? 'table-menus notAllowed' : 'table-menus',
            body: {
              options: [_menuConfig || []],
            },
          }
        }

        if (this.hasOpenEdit) {
          gridOptionsData.editConfig = {
            trigger: 'manual',
            mode: 'row',
            showStatus: true,
            showInsertStatus: true,
            autoClear: false,
          }
        }
        if (this.info.extension.clickEdit.value.open && this.info.extension.clickEdit.value.editRules) {
          let obj = {}
          this.info.extension.clickEdit.value?.editRules?.forEach((row) => {
            obj[row.key] = []
            if (row.required) {
              obj[row.key].push({ required: true, message: '请输入必填项' })
            }
            if (row.pattern) {
              obj[row.key].push({ pattern: row.pattern, message: row.message })
            }
            obj[row.key].push({
              validator: (r) => {
                if (!this.editRowCalculation(r.row)) {
                  return new Error(this.info.extension.clickEdit.value.editCalculate?.msg)
                } else {
                  return true
                }
              },
            })
          })
          gridOptionsData.editRules = obj
        }

        // 写入对齐方式配置
        if (this.info.extension.align && this.info.extension.align.value) {
          gridOptionsData.align = this.info.extension.align.value
        }

        // 展开行配置
        if (this.info.extension.expendRow && this.info.extension.expendRow.value && this.info.extension.expendRow.value.open) {
          gridOptionsData.expandConfig = {
            trigger: this.info.extension.expendRow.value.clickRowTrigger ? 'row' : 'default',
          }
        }

        return gridOptionsData
      },
      getPageSize() {
        return Number(this.info.extension.pageSize.value)
      },
      getInfo() {
        return this.info
      },
      getExtension() {
        return this.info.extension
      },
      //是否是单选或者多选
      hasCheckboxOrRadio() {
        let _type = ''
        this.getExtension.tableColumns.value.forEach((v) => {
          if (v._type == 'checkbox') {
            _type = 'checkbox'
          }
          if (v._type == 'radio') {
            _type = 'radio'
          }
        })
        return _type
      },
      getTableColumns() {
        //操作按钮
        let operateMenu = []
        // 判断已有的表格列里面有没有操作列
        let hasOperate = false
        this.info.extension.tableColumns.value.forEach((i) => {
          if (i._type === 'operate') hasOperate = true
        })
        if (this.info.extension.operateMenuConfig && this.info.extension.operateMenuConfig.value.length > 0 && !hasOperate) {
          let _width = 0
          this.info.extension.operateMenuConfig.value.forEach((v) => {
            if (v.extension.circle.value) {
              _width += 40
            } else {
              _width += 80
            }
          })

          operateMenu = [
            {
              _type: 'operate',
              showOverflow: true,
              title: '操作',
              width: _width,
              fixed: this.info.extension.operateMenuConfig.setting.fixed,
              slots: {
                // default: 'operate',
                default: ({ row, column }) => {
                  return [
                    <div class="flex justify-center">
                      {this.getOperateMenu.map((v) => {
                        if (!this.handleStatusConfig(row, v)) {
                          return (
                            <el-button
                              onClick={() => this.operateClick(v, row, column)}
                              circle={v.extension.circle.value}
                              plain={v.extension.plain.value}
                              round={v.extension.round.value}
                              type={v.extension.type.value}
                            >
                              {() => {
                                if (v.extension.icon.value) {
                                  if (!v.extension.circle.value) {
                                    return (
                                      <span>
                                        <vui-icon icon={v.extension.icon.value} />
                                        {v.name}
                                      </span>
                                    )
                                  }
                                  return <vui-icon icon={v.extension.icon.value} />
                                } else {
                                  return <span>{v.name}</span>
                                }
                              }}
                            </el-button>
                          )
                        } else {
                          return ''
                        }
                      })}
                    </div>,
                  ]
                },
              },
            },
          ]
        }
        let _tableColumns = [...cloneDeep(this.info.extension.tableColumns.value), ...operateMenu, ...this.batchAttributeColumns]
        return this.createTableColumn(_tableColumns, true)
      },
      getExpandTableColumns() {
        let _tableColumns = cloneDeep(this.info.extension.expandTableColumns.value)
        console.log('getExpandTableColumns', this.createTableColumn(_tableColumns))
        return this.createTableColumn(_tableColumns)
      },
      getOperateMenu() {
        return this.info.extension.operateMenuConfig.value
      },
      getRowStatusConfig() {
        return this.info.extension.rowStatusConfig.value
      },
      getCellStatusConfig() {
        return this.info.extension.cellStatusConfig && this.info.extension.cellStatusConfig.value
      },
      getColumnStatusConfig() {
        return this.info.extension.columnStatusConfig && this.info.extension.columnStatusConfig.value
      },
      getEditDefault() {
        return this.info.extension.clickEdit.value.editDefault
      },
      getExpandAll() {
        const tableData = this.$refs[this.info._id].getData()
        return this.expandCount === tableData.length
      },
      getPrimaryKey() {
        return this.info.extension.primaryKeyField ? this.info.extension.primaryKeyField.value : ''
      },
      getKeppSelect() {
        return this.info.extension.keepSelect ? this.info.extension.keepSelect.value : false
      },
    },
    watch: {
      getData: {
        immediate: true,
        handler: function (newval) {
          this.list = newval
          this.tableLoadData(newval)
        },
      },
    },
    created() {
      this.hasOpenEdit = this.getInfo.extension.clickEdit ? this.getInfo.extension.clickEdit.value.open : false
      // 如果当前表格开启了编辑模式 则关闭横向虚拟滚动
      if (this.hasOpenEdit) {
        this.scrollXConfig.enabled = false
      }
      // 抽取头部按钮组件 只保留按钮类型组件 方便宽度计算与按钮折叠
      this.showButtonList = this.extractButton()
      this.$sub(`SplitpaneResized_${this.previewPageId()}`, () => {
        this.getHeight()

        setTimeout(() => {
          this.getTableWidthProportion()
          // 计算按钮区域布局
          this.disposeButton()
          // console.log('表格宽度变化', this.getTableRef().$el, this.getTableRef().$el.clientWidth)
        }, 200)
      })

      // 加载表格列编辑配置
      this.tableColumnEdit()
    },
    mounted() {
      this.columnDrop()
      // 初始化赋值
      this.setFormData(1, this.getPageSize)
      this.cacheFormData = cloneDeep(this.getInfo.data.formData)
      // console.log('this.getTableColumns', this.getTableColumns)
      // this.tableLoadColumn(this.getTableColumns)

      this.$nextTick(() => {
        this.getHeight()
      })

      this.batchAttributeInit()
    },
    methods: {
      translateTitle,
      saveSelectedRows() {
        this.keepSelectData = this.getCheckboxOrRadioVals()
      },
      setkeepSelectData() {
        const tableData = this.$refs[this.info._id].getData()
        const selectedRows = []
        this.keepSelectData.forEach((i) => {
          const currentRow = findListItem(i, this.getPrimaryKey, tableData)
          currentRow && selectedRows.push(currentRow)
        })
        this.setCheckboxRow(selectedRows, true)
      },
      expandAll(checked) {
        if (checked) {
          const tableData = this.$refs[this.info._id].getData() || []
          const expandRows = this.$refs[this.info._id].getRowExpandRecords() || []
          tableData.forEach((i) => {
            if (expandRows.indexOf(i) === -1) this.toggleRowExpand({ expanded: true, row: i })
          })
          this.expandCount = tableData.length
          this.$refs[this.info._id].setAllRowExpand(true)
        } else {
          this.expandCount = 0
          this.$refs[this.info._id].clearRowExpand()
        }
      },
      // 表格行展开状态改变
      toggleRowExpand({ expanded, row }) {
        if (expanded) {
          this.expandCount++
          // 展开时调用接口
          if (!this.info.extension.expendRow.value.api) return
          const params = {}
          this.info.extension.expendRow.value.requestData.forEach((i) => {
            params[i.key] = processingConstant(this, i.value)
            if (/#{.*?}/g.test(i.value)) {
              // 变量解析
              params[i.key] = replaseRegVariable(i.value, row)
            }
          })
          request({
            url: GFCD('dams', 'domain') + this.info.extension.expendRow.value.api,
            method: 'post',
            data: {
              data: JSON.stringify({ ...row, ...params }),
              method: this.info.extension.expendRow.value.method,
            },
          })
            .then((res) => {
              const { getDataKey } = this.info.extension.expendRow.value
              this.expandData[row._X_ROW_KEY] = isEmpty(getDataKey) ? res.data : res.data[getDataKey].data
            })
            .catch(() => {
              this.expandData[row._X_ROW_KEY] = []
            })
        } else {
          this.expandCount--
        }
      },
      // 表格列转化函数
      createTableColumn(_tableColumns, notExpandRow) {
        // 如果开启了展开行则添加展开行
        if (notExpandRow && this.info.extension.expendRow && this.info.extension.expendRow.value.open) {
          _tableColumns.unshift({
            type: 'expand',
            width: '60',
            slots: {
              content: 'expand_row_slot',
              header: 'expand_col_header',
            },
          })
        }
        // 获取开启了列状态的列
        const customCol = []
        this.info.extension.columnStatusConfig &&
          this.info.extension.columnStatusConfig.value.forEach((i) => {
            const config = i.extension.statusConfig.value
            config.target && customCol.push(config.target)
          })

        _tableColumns.forEach((v) => {
          // 载入提示信息配置
          if (v.tipMessage) {
            v.titlePrefix = {
              content: v.tipMessage,
              icon: 'ri-question-fill',
            }
          }

          v.width = `${v.width}px`
          v['minWidth'] = v.title && typeof v.title == 'string' ? v.title.length * 22 + 'px' : '70px'
          if (notExpandRow && v._type === 'checkbox') {
            v['width'] = '60px'
            v.slots = {
              header: 'checkbox_header',
            }
          }

          if (v._type === 'seq') {
            v['width'] = '50px'
          }
          if (notExpandRow && v._type === 'switch') {
            v.slots = {
              default: v.field,
            }
            this.switchSlots.push({ field: v.field, formItemType: v.formModuleType || {} })
          }
          if (notExpandRow && v._type === 'select') {
            v.slots = {
              default: v.field,
            }
            const selectItem = { field: v.field, formItemType: v.formModuleType || {}, options: [] }
            this.selectSlots.push(selectItem)
            this.getSelectOptions(v, selectItem)
          }
          if (notExpandRow && v._type === 'input') {
            v.slots = {
              default: v.field,
            }
            this.inputSlots.push({ field: v.field, formItemType: v.formModuleType || {} })
          }
          if (notExpandRow && v._type === 'columnEdit') {
            // 表格列编辑
            v.slots = {
              default: `columnEdit_${v.field}`,
            }
            this.columnEditSlots.push({ field: v.field, formItemType: v.formModuleType || {} })
          }
          v['showHeaderOverflow'] = true
          v['searchConfig'] = v['searchConfig'] || {}

          //做进度条转换
          if (v._type === 'progress') {
            v.slots = {
              default: ({ row, column }) => {
                let val = row[column.property] || 0
                return [
                  <a title={val}>
                    <el-progress percentage={val} stroke-width={16} text-inside={true} />
                  </a>,
                ]
              },
              edit: v.field,
            }
          }

          // 做标签自定义渲染
          if (v._type === 'tag') {
            v.slots = {
              default: ({ row, column }) => {
                const value = row[column.field]
                const color = this.tagCellStyle({ row, column }) || { color: '#409eff', backgroundColor: '#ecf5ff' }
                const attrObj = {
                  style: { color: color.color, borderColor: color.borderColor || color.color },
                  color: color.backgroundColor,
                }
                const iconStyle = {
                  style: { color: color.iconColor, marginRight: '5px' },
                }
                return color.icon
                  ? [
                      <el-tag {...attrObj}>
                        <vui-icon icon={color.icon} {...iconStyle} />
                        {value}
                      </el-tag>,
                    ]
                  : [<el-tag {...attrObj}>{value}</el-tag>]
              },
              edit: v.field,
            }
          }

          // 将字段类型做自定义渲染 方便列状态判断之后添加内容
          // const customCellRender = (row, column) => {
          //   const colorObj = this.cellCustomStyle[`${column.field}_${row[column.field]}`] || {}
          //   const tagStyle = {
          //     type: colorObj.tagType,
          //   }
          //   const iconStyle = {
          //     style: { color: colorObj.iconColor },
          //   }
          //   if (colorObj.icon && colorObj.tagContent) {
          //     return [
          //       <p>
          //         <vui-icon icon={colorObj.icon} {...iconStyle} />
          //         <el-tag {...tagStyle}>{colorObj.tagContent}</el-tag>
          //         <span>{row[column.field]}</span>
          //       </p>,
          //     ]
          //   } else if (colorObj.icon) {
          //     return [
          //       <p>
          //         <vui-icon icon={colorObj.icon} {...iconStyle} />
          //         <span>{row[column.field]}</span>
          //       </p>,
          //     ]
          //   } else if (colorObj.tagContent) {
          //     return [
          //       <p>
          //         <el-tag {...tagStyle}>{colorObj.tagContent}</el-tag>
          //         <span>{row[column.field]}</span>
          //       </p>,
          //     ]
          //   } else {
          //     return [
          //       <p>
          //         <span>{row[column.field]}</span>
          //       </p>,
          //     ]
          //   }
          // }
          if (v._type === 'field' && customCol.indexOf(v.field) > -1) {
            v.slots = {
              default: 'custom_cell_slot',
            }
          }

          //是否开启编辑 添加配置文件
          if (notExpandRow && v.openEdit && this.hasOpenEdit) {
            v.editRender = {}
            if (v.slots) {
              v.slots['edit'] = v.field
            } else {
              v.slots = {
                edit: v.field,
              }
            }

            // this.editSlots.push(v.field)
            this.editSlots.push({
              field: v.field,
              formItemType: v.formModuleType || {},
            })
          } else {
            if (v.slots) {
              delete v.slots.edit
            }
          }
        })

        // if (this.development) {
        //   return _tableColumns
        // } else {
        //   if (
        //     this.getInfo.type.indexOf('uiSelectLayerNew') > -1 ||
        //     (this.getInfo.extension.batchAttribute && this.getInfo.extension.batchAttribute.value.open)
        //   ) {
        //     return _tableColumns
        //   } else {
        //     return _tableColumns.filter(
        //       (el) => el.isChecked || el.isChecked === undefined || el._type == 'seq' || el._type == 'checkbox' || el._type == 'radio'
        //     )
        //   }
        //   // return _tableColumns
        //   //筛选下根据权限来渲染表头；根据表头字段isChecked为true或者为undefined(提示：因初始设置表头时没有设置这个参数，初始需要全部显示)
        // }
        return _tableColumns
      },
      // 表格列编辑配置
      tableColumnEdit() {
        if (!this.info.extension.tableColumnEdit) return
        this.columnEditConfig = this.info.extension.tableColumnEdit.value
        if (this.columnEditConfig.open) {
          // 打开了列配置模式
        }
      },
      notIsMac() {
        return (function () {
          return /macintosh|mac os|AppleWebKit|Chrome x/i.test(navigator.userAgent)
        })()
      },
      // 粘贴事件处理函数
      pasteEventFunc(e) {
        const classNames = e.target.offsetParent ? e.target.offsetParent.className.split(' ') : []
        if (classNames.indexOf('tableColumnEdit') > -1) {
          e.preventDefault()
          const clipdata = e.clipboardData || window.clipboardData
          const clipText = clipdata ? clipdata.getData('text/plain') : ''
          // 找到当前触发事件的行ID
          const currentRowKey = classNames.find((i) => i.indexOf('rowId') > -1)
          const currentRowId = currentRowKey.split('-')[1]
          // 获取表格全部数据
          const tableData = this.getTableRef() ? this.getTableRef().getTableData().fullData : []
          // 粘贴起始的下标
          let startIndex = 0
          tableData.forEach((item, index) => {
            if (item._X_ROW_KEY === currentRowId) startIndex = index
          })
          // 获取到行数据
          let rowDatas = clipText.split('\r\n')
          // 判断mac
          rowDatas = this.notIsMac() ? rowDatas : rowDatas[0].split('\n')
          // 编辑列字段
          const columnFieldList = this.columnEditConfig.editColumns.split(',')
          // 粘贴的起始字段
          let startFieldIndex = 0
          const startField = currentRowKey.split('-')[2]
          columnFieldList.forEach((item, index) => {
            if (item === startField) startFieldIndex = index
          })
          // 遍历行数据 进行列数据赋值
          rowDatas.forEach((rowItem) => {
            if (rowItem) {
              const colDatas = rowItem.split('\t')
              let fieldIndex = startFieldIndex
              // 行数据赋值
              for (let i = 0; i < colDatas.length; i++) {
                const colField = columnFieldList[fieldIndex] && trim(columnFieldList[fieldIndex])
                // 如果没有找到对应的列字段 则代表复制的列数大于可编辑的列数 则跳出此次循环
                if (!colField) continue
                tableData[startIndex] && (tableData[startIndex][colField] = trim(colDatas[i]) || '')
                fieldIndex++
              }
              startIndex++
            }
          })
        }
      },
      // 进入列编辑模式
      intoColumnEditModel() {
        if (!this.getHasPreview) return
        // 修改对应字段列的type
        const columnList = this.columnEditConfig.editColumns.split(',')
        this.info.extension.tableColumns.value.forEach((colItem) => {
          if (columnList.indexOf(colItem.field) > -1) {
            // 如果在可编辑列里面 则修改type标识
            colItem._type = 'columnEdit'
          }
        })
        // 进入列编辑模式
        this.columnEditModule = true
        window.addEventListener('paste', this.pasteEventFunc)
      },
      // 退出列编辑模式
      outColumnEditModel() {
        // 修改对应字段列的type
        const columnList = this.columnEditConfig.editColumns.split(',')
        this.info.extension.tableColumns.value.forEach((colItem) => {
          if (columnList.indexOf(colItem.field) > -1) {
            // 如果在可编辑列里面 则修改type标识
            colItem._type = 'field'
          }
        })
        // 退出列编辑模式
        this.columnEditModule = false
        // 清除事件
        window.removeEventListener('paste', this.pasteEventFunc)
      },
      // 保存列编辑数据
      saveColumnEdit() {
        if (this.loading) return
        // 获取表格全部数据
        const tableData = this.getTableRef() ? this.getTableRef().getTableData().fullData : []
        let requireFlag = true
        if (this.columnEditConfig.require) {
          // 开启了必填校验
          const columnFieldList = this.columnEditConfig.editColumns.split(',')
          tableData.forEach((dataItem) => {
            columnFieldList.forEach((fleidItem) => {
              const field = trim(fleidItem)
              if (!dataItem[field]) requireFlag = false
            })
          })
        }
        if (!requireFlag) {
          // 校验不通过则提示用户
          this.$baseMessage('请输入必填项！', 'error')
          return
        }
        // 提交数据
        this.loading = true
        request({
          url: GFCD('dams', 'domain') + this.getInfo.extension.api.value,
          method: 'post',
          data: {
            data: JSON.stringify(tableData),
            method: this.columnEditConfig.method,
          },
        })
          .then(() => {
            this.loading = false
            this.$baseMessage(`保存成功!`, 'success')
            // 退出编辑模式
            this.outColumnEditModel()
          })
          .catch(() => {
            this.loading = false
          })
      },
      // 撤销表格编辑
      revertData(row, field, model) {
        console.log(row, field)
        this.getTableRef().revertData(row, field)
        model && this.getTableRef().revertData(row, model)
      },
      saveToTable({ data, showCustomOption }) {
        if (data.length > 0) {
          this.tableLoadColumn(data)
          // wms 直接覆盖json
          this.info.extension.tableColumns.value = data
        }

        this.showCustomOption = showCustomOption
      },
      // 抽取按钮组件函数
      extractButton() {
        let buttonList = []
        const eachFunc = (obj) => {
          if (
            obj.type === 'uiButton' ||
            obj.type === 'uiDownload' ||
            obj.type === 'uiTolead' ||
            obj.type === 'uiDropdown' ||
            obj.type === 'uiPrint' ||
            obj.type === 'uiUpload'
          ) {
            buttonList.push(obj)
          }
          obj.list &&
            obj.list.forEach((item) => {
              eachFunc(item)
            })
          obj.pageModules &&
            obj.pageModules.forEach((item) => {
              eachFunc(item)
            })
        }
        eachFunc(this.info)
        return buttonList
      },
      // 计算按钮区域展示状态
      disposeButton() {
        // 获取容器宽度
        const buttonBoxWidth = this.$refs[this.info._id + '_buttonBox'] && this.$refs[this.info._id + '_buttonBox'].clientWidth
        // console.log('获取容器宽度 ------------------------ 获取容器宽度', this.info._id, buttonBoxWidth)
        // 先找到全部的按钮组件的ID
        let foldButtonList = [] // 折叠的按钮组
        let buttonList = [] // 不折叠的按钮组
        let buttonsWidth = 0 // 不折叠的按钮的宽度
        let overflowing = false // 是否溢出
        const eachFunc = (obj) => {
          if (
            obj.type === 'uiButton' ||
            obj.type === 'uiDownload' ||
            obj.type === 'uiTolead' ||
            obj.type === 'uiDropdown' ||
            obj.type === 'uiPrint' ||
            obj.type === 'uiUpload'
          ) {
            const btnDom = this.vuiComponents[obj._id] && this.vuiComponents[obj._id].ref
            // 缓存宽度 防止隐藏组件后ref拿不到导致页面报错
            try {
              // 如果是tab切换页的第二页的组件 则获取宽度时是没有值的 这个时候需要设置一个默认值
              if (!this.buttonWidthObj[obj._id]) this.buttonWidthObj[obj._id] = btnDom.$el.offsetWidth || 62 + 4
            } catch (error) {
              console.warn(error)
              // 有些时候获取组件DOM实例会报错 为确保计算不出现问题 则默认组件为普通按钮 宽度赋值为普通按钮宽度
              if (!this.buttonWidthObj[obj._id]) this.buttonWidthObj[obj._id] = 62
            }

            if (overflowing) {
              // 如果宽度已经溢出 则直接添加组件进折叠按钮组
              foldButtonList.push(obj)
            } else {
              if (buttonsWidth + this.buttonWidthObj[obj._id] > buttonBoxWidth) {
                // 按钮宽度超出容器宽度
                overflowing = true
                foldButtonList.push(obj)
              } else {
                // 宽度未超出则只记录宽度
                buttonsWidth += this.buttonWidthObj[obj._id]
                buttonList.push(obj)
              }
            }
          }
          obj.list &&
            obj.list.forEach((item) => {
              eachFunc(item)
            })
          obj.pageModules &&
            obj.pageModules.forEach((item) => {
              eachFunc(item)
            })
        }
        eachFunc(this.info)
        // console.log(`溢出了哟 ………………………………………… ${this.info._id}`, buttonBoxWidth, buttonList, foldButtonList)
        // console.log(overflowing)
        // 如果宽度未溢出且之前也未溢出 则不做操作
        if (!overflowing && !this.buttonIsOverflowing) {
          return
        } else {
          // console.log('溢出了哟 …………………………………………', buttonList, foldButtonList)
          this.showButtonList = buttonList
          this.foldButtonList = foldButtonList
          this.buttonIsOverflowing = overflowing
        }
      },
      // 键盘事件
      handlerKeyDown({ $event }) {
        if (this.editModel && $event && $event.key === 'Escape') {
          // 退出编辑模式
          this.editModel = false
          // esc 键不保存数据
          this.isNotSaveData = true
          const { column, row } = this.getTableRef().getEditRecord()
          this.getTableRef() && this.getTableRef().clearEdit()
          this.editClosedEvent({ column, row })
          // 如果是新增表格数据动作进入的编辑模式 则需要删除第一条数据
          if (this.isAddTableEdit) {
            this.info.data.requestData.data.shift()
            this.getTableRef() && this.getTableRef().loadData(this.info.data.requestData.data)
          }
        } else if (this.editModel && $event.ctrlKey && $event.keyCode === 83) {
          // 当按下Ctrl + S 时则保存编辑数据
          $event.preventDefault() // 阻止默认事件
          // 获取当前编辑的数据 (这里将后续逻辑放到页面重载之后，先触发数值输入框的改变，确保提交的是正确的值)
          this.$nextTick(() => {
            const { column, row } = this.getTableRef().getEditRecord()
            // 校验数据
            this.getTableRef() &&
              this.getTableRef()
                .validate(row)
                .then((valid) => {
                  if (!valid) {
                    // 校验通过走下一步
                    this.editModel = false
                    this.isNotSaveData = false
                    this.getTableRef() && this.getTableRef().clearEdit()
                    // 调用退出编辑事件
                    this.editClosedEvent({ column, row }).then(async () => {
                      // 如果配置了刷新表格数据 则刷新数据并触发点击
                      if (!this.isAddTableEdit && this.info.extension.clickEdit.value.refreshTable) {
                        await this.$refreshTable(true)
                        this.$nextTick(() => {
                          const tableData = this.$refs[this.info._id].getData()
                          const currentRow = findListItem(row, this.getPrimaryKey, tableData)
                          this.cellClickEvent({ row: currentRow })
                        })
                      }
                    })
                  }
                })
            // 调用退出编辑模式方法
            // this.editClosedEvent({ row, column })
          })
        }
        if (this.info.extension.udownKeyHandover && this.info.extension.udownKeyHandover.value) {
          // 如果开启了上下键切换功能
          // 先获取当前选中行
          const currentRowData = this.getCheckboxOrRadioVals()[0]
          // 再获取当前选中行的下标
          const currentIndex = this.getTableRef().getRowSeq(currentRowData) - 1
          let nextData = null
          // 获取下一条数据
          if ($event && $event.key === 'ArrowDown') {
            nextData = this.getTableRef().getData(currentIndex + 1)
          } else if ($event && $event.key === 'ArrowUp') {
            nextData = this.getTableRef().getData(currentIndex - 1)
          }
          // 触发表格双击
          nextData && this.cellDBLClickEvent({ row: nextData })
        }
      },
      // 进入编辑模式
      enterEditModel(isAddTableData, addTableDataEventObj) {
        // console.log('进入编辑模式')
        this.isAddTableEdit = isAddTableData || false
        if (isAddTableData) {
          // 如果是通过新增表格数据进入的编辑模式 则需要记录状态以及进入第一行数据的编辑模式
          this.addTableDataEventObj = addTableDataEventObj
        }

        // 获取高亮的当前行数据
        let currentRecord = this.getTableRef() && this.getTableRef().getCurrentRecord()
        // console.log('currentRecord --------------- ', currentRecord)
        if (!currentRecord || isAddTableData) {
          // 如果没有当前高亮数据 或者是通过新增表格数据进入的编辑模式 则使用表格第一行数据
          currentRecord = this.getTableRef() && this.getTableRef().getTableData().fullData && this.getTableRef().getTableData().fullData[0]
        }
        if (!currentRecord) return
        // 进入编辑模式
        this.editModel = true
        // 默认退出时保存数据
        this.isNotSaveData = false
        // 先清空上一次编辑模式下的编辑单元列表
        this.$store.dispatch('tableFormItem/clearTableFormItemList')
        this.$refs[this.info._id].setEditRow && this.$refs[this.info._id].setEditRow(currentRecord)
        // 自动聚焦第一个可编辑单元
        setTimeout(() => {
          const moduleList = this.$store.getters['tableFormItem/getTableFormItemList']
          if (moduleList[0] && moduleList[0].ref) {
            moduleList[0].ref.focus()
            moduleList[0].ref.select && moduleList[0].ref.select()
          }
        })
      },
      // 退出编辑模式
      quitEditModel() {
        // console.log('退出编辑模式')
        this.editModel = false
        // 需要保存表格数据
        this.isNotSaveData = false
        const { column, row } = this.getTableRef().getEditRecord()
        this.getTableRef() && this.getTableRef().clearEdit()
        this.editClosedEvent({ column, row })
      },
      async editNextRow() {
        // 编辑表格下一行
        this.isNotSaveData = false
        let { column, row } = this.$refs[this.info._id].getEditRecord && this.$refs[this.info._id].getEditRecord() // 当前行
        this.$refs[this.info._id].clearEdit() // 先退出编辑模式
        await this.editClosedEvent({ column, row }) // 调用退出编辑事件
        // 如果配置了刷新表格 则需要先刷新再编辑下一行
        if (this.info.extension.clickEdit.value.refreshTable) {
          // 需要刷新表格(不重置页码)，刷新之后自动触发当前行的点击事件
          await this.$refreshTable(true)
          const tableData = this.$refs[this.info._id].getData()
          row = findListItem(row, this.getPrimaryKey, tableData)
        }
        // 如果配置了不编辑表格下一行则触发之前行点击事件并退出
        if (this.info.extension.clickEdit.value.enterNotEditNextRow) {
          this.cellClickEvent({ row: row })
          return
        }

        const currentIndex = this.$refs[this.info._id].getRowIndex(row)
        const nextRow = this.$refs[this.info._id].getTableData && this.$refs[this.info._id].getTableData().fullData[currentIndex + 1]
        if (nextRow && !this.isAddTableEdit) {
          // 如果有下一行数据 且不是新增表格数据进入的编辑模式 则下一行数据进入编辑模式
          this.$refs[this.info._id].setEditRow && this.$refs[this.info._id].setEditRow(nextRow)
          // 自动聚焦第一个可编辑单元
          setTimeout(() => {
            const moduleList = this.$store.getters['tableFormItem/getTableFormItemList']
            if (moduleList[0] && moduleList[0].ref) {
              moduleList[0].ref.focus()
              moduleList[0].ref.select && moduleList[0].ref.select()
            }
          })
        }
        // 触发下一行的点击事件
        this.cellClickEvent({ row: nextRow })
      },
      // 表格编辑列改变
      editFormItemChange(val) {
        this.editFormItem = val
      },
      formDataItemChange(row, newVal) {
        // console.log('表格这边值改变了！！', row, newVal)
        Object.assign(row, newVal)
      },
      tableSwitch(row, i, v) {
        if (v.formItemType && v.formItemType.api && v.formItemType.method) {
          const requestDatas = v.formItemType.customParams || []
          const customDataObj = {}
          requestDatas.forEach((item) => {
            customDataObj[item.key] = processingConstant(this, item.value)
            if (/{[^#{]+}/g.test(customDataObj[item.key])) {
              customDataObj[item.key] = replaseRegVariable(customDataObj[item.key], { ...row, ...this.info.data.formData })
            }
          })
          return request({
            url: GFCD('dams', 'domain') + v.formItemType.api,
            method: 'post',
            data: {
              data: JSON.stringify({ ...row, ...customDataObj }),
              method: v.formItemType.method,
            },
          }).then((res) => {
            this.loading = false
            //解密
            if (v.formItemType.actions) {
              actionsTask(
                this,
                this.info,
                v.formItemType.actions,
                row,
                () => {
                  console.log('完成了')
                },
                'colSave',
                res
              )
            }
            this.$baseMessage('修改成功', 'success')
          })
        } else {
          console.log('开关请配置api')
        }
      },
      // 請求渲染下拉組件時的選項列表
      getSelectOptions(v, selectRenderItem) {
        // const field = v.field
        const { getOptionsApi, getOptionsMethod, requestDatas, getDataKey } = v.formModuleType
        if (!getOptionsApi) return
        const requestDataObj = {}
        requestDatas.forEach((item) => {
          requestDataObj[item.key] = processingConstant(this, item.value)
        })
        return request({
          url: GFCD('dams', 'domain') + getOptionsApi,
          method: 'post',
          data: {
            data: JSON.stringify(requestDataObj),
            method: getOptionsMethod,
          },
        }).then((res) => {
          const options = isEmpty(getDataKey) ? res.data : res.data[getDataKey].data
          selectRenderItem.options = isArray(options) ? options : []
        })
      },
      // 编辑模式下计算行规则
      editRowCalculation(row) {
        if (!(this.info.extension.clickEdit.value.editCalculate && this.info.extension.clickEdit.value.editCalculate.value)) return true
        if (this.info.extension.clickEdit.value.editCalculate) {
          try {
            return eval(replaseRegVariable(this.info.extension.clickEdit.value.editCalculate.value, row))
          } catch (error) {
            return false
          }
        } else {
          return false
        }
      },

      addressClickEvent(row) {
        console.log('row', row)
      },
      getTableWidthProportion() {
        if (this.getTableRef() && this.getTableRef().$el) {
          let _tableWidth = this.getTableRef().$el.clientWidth
          let _winWidth = document.body.clientWidth
          // console.log('表格宽度变化', this.getTableRef().$el, _tableWidth, _winWidth, parseFloat((_tableWidth / _winWidth) * 100))
          let _proportion = parseFloat((_tableWidth / _winWidth) * 100)
          this.hasMini = _proportion <= 30 ? true : false
        }
      },
      handleStatusConfig(row, config) {
        let _status = false
        let expressionArr = []
        if (config.extension && config.extension.statusConfig && config.extension.statusConfig.value.length > 0) {
          let _statusConfig = config.extension.statusConfig.value
          // console.log('bbfpl 2', config)
          _statusConfig.forEach((item, index) => {
            let _val = processingConstant(this, item.value)
            if (item.conditions == '1') {
              if (row[item.key] == _val && item.execution == 'hide') {
                expressionArr.push(true)
              } else {
                expressionArr.push(false)
              }
            }
            if (item.conditions == '2') {
              if (row[item.key] != _val && item.execution == 'hide') {
                expressionArr.push(true)
              } else {
                expressionArr.push(false)
              }
            }
            if (index + 1 < _statusConfig.length) {
              expressionArr.push(item.operator || 'or')
            }

            // if (item.conditions == '1') {
            //   if (row[item.key] == _val && item.execution == 'hide') {
            //     _status = true
            //   }
            // }
            // if (item.conditions == '2') {
            //   if (row[item.key] != _val && item.execution == 'hide') {
            //     _status = true
            //   }
            // }
          })
        }
        if (expressionArr.length <= 0) {
          return false
        }

        let expression = ''
        expressionArr.forEach((v) => {
          let _v = v
          if (v == 'or') {
            _v = '||'
          }
          if (v == 'and') {
            _v = '&&'
          }
          expression = `${expression} ${_v}`
        })

        try {
          _status = new Function('return ' + expression)()
        } catch (error) {
          console.log('表格计算出错 -- ', error)
        }
        // console.log('bbfpl expressionArr1', config.name, expressionArr, expression, _status)
        return _status
      },
      tableLoadColumn(columns) {
        if (isEmpty(columns)) {
          columns = []
        }
        this.getTableRef() && this.getTableRef().reloadColumn(columns)
      },
      tableLoadData(data) {
        if (isEmpty(data)) {
          data = []
          // return
        }
        this.getTableRef() && this.getTableRef().loadData(data)
      },
      getTableRef() {
        return this.$refs[this.getInfo._id]
      },

      getHeight() {
        setTimeout(() => {
          let _domHeight = domHeight(this)
          // console.log('_domHeight 表格', _domHeight)
          if (_domHeight > 0) {
            this.tabelHeight = _domHeight
            this.tabelHeight = this.getInfo.height || this.tabelHeight
          }
        }, 300)
      },
      dataSourceChange(newval) {
        if (this.getInfo.dataSourceBind.hasParam.value) {
          let _mergeData = {}
          // 根据 getDataKey 筛选需要的数据
          if (!trim(this.dataSource.getDataKey)) {
            // 如果没有 getDataKey 则返回全量数据
            _mergeData = newval
          } else {
            const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
            isArray(keyList) &&
              keyList.forEach((item) => {
                item = trim(item)
                if (newval[item] !== undefined) {
                  // 如果传过来的对象里面没有要取得值 则丢弃
                  _mergeData[item] = newval[item]
                }
              })
          }
          this.getInfo.data.formData = {
            ...this.getInfo.data.formData,
            ..._mergeData,
          }
          //数据源变化后重新执行
          if (this.dataSourceChangeIndex != 0) {
            this.onLoad()
          }
        } else {
          this.list = newval.data
          this.tableLoadData(newval.data)
          // 缓存数据源绑定的值，以供自定义参数的变量获取使用
          let dataSourceFormData = {}
          const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
          isArray(keyList) &&
            keyList.forEach((item) => {
              item = trim(item)
              if (newval[item] !== undefined) {
                // 如果传过来的对象里面没有要取得值 则丢弃
                dataSourceFormData[item] = newval[item]
              }
            })
          this.dataSourceFormData = dataSourceFormData
        }
        this.dataSourceChangeIndex++
      },
      setFormData(currentPage, pageSize) {
        this.getInfo.data.formData['#LIMIT#'] = currentPage
        this.getInfo.data.formData['#PAGE_SIZE#'] = pageSize
        this.pageSize = pageSize
      },
      //
      rowStyle({ row }) {
        // console.log('this.getRowStatusConfig ------------- ', this.getRowStatusConfig)
        if (this.getRowStatusConfig && this.getRowStatusConfig.length > 0) {
          let color = {}
          this.getRowStatusConfig.forEach((v) => {
            // console.log('计算结果 ------------- ', row[v.key], v.value, row[v.key] === v.value)
            if (row[v.key] === v.value) {
              color = {
                backgroundColor: v.color,
                color: v.textColor == undefined ? '#000000' : v.textColor,
              }
            }
          })
          if (!isEmpty(color)) {
            return color
          }
        }
      },
      // 表格列状态配置
      cellStyle({ row, column }) {
        let isTag = false
        if (this.info.extension.tableColumns && this.info.extension.tableColumns.value) {
          this.info.extension.tableColumns.value.forEach((item) => {
            if (item.field === column.field && item._type === 'tag') {
              isTag = true
            }
          })
        }
        if (isTag) return
        if (this.getCellStatusConfig && this.getCellStatusConfig.length > 0) {
          let color = {}
          this.getCellStatusConfig.forEach((v) => {
            if (column.field === v.key && row[v.key] !== undefined && row[v.key] === v.value) {
              color = {
                backgroundColor: v.color,
                color: v.textColor == undefined ? '#000000' : v.textColor,
              }
            }
          })
          if (!isEmpty(color)) {
            return color
          }
        }
        if (this.getColumnStatusConfig && this.getColumnStatusConfig.length > 0) {
          let color = this.calculateColumnColor({ row, column })
          if (!isEmpty(color)) {
            return color
          }
        }
      },
      // 根据条件判断出列的颜色
      calculateColumnColor({ row, column }) {
        let color = ''
        this.getColumnStatusConfig.forEach((item) => {
          let config = item.extension.statusConfig.value
          let list = config.conditionList
          let symbolMap = {
            1: '==',
            2: '!=',
            3: '>',
            4: '>=',
            5: '<',
            6: '<=',
            or: '||',
            and: '&&',
          }
          let conditionStr = ''
          // 将多个条件合并成类似(a>0 && a<=10 || b!=1)的这种形式
          list.forEach((v, index) => {
            conditionStr += `'${row[v.key]}' ${symbolMap[v.conditions]} '${v.value}'`
            if (index < list.length - 1) {
              conditionStr += symbolMap[v.operator]
            }
          })
          let result = eval(conditionStr)
          // list.forEach((v) => {
          if (column.field === config.target && result) {
            color = {
              backgroundColor: config.color,
              color: config.textColor == undefined ? '#000000' : config.textColor,
              borderColor: config.borderColor || '',
              icon: config.icon || '',
              iconColor: config.iconColor || '',
              tagContent: config.tagContent || '',
              tagType: config.tagType || '',
            }
            if (config.icon || config.tagContent) {
              if (
                !(
                  this.cellCustomStyle[`${column.field}_${row[column.field]}`] &&
                  this.cellCustomStyle[`${column.field}_${row[column.field]}`].toString === color.toString
                )
              ) {
                this.cellCustomStyle[`${column.field}_${row[column.field]}`] = cloneDeep(color)
              }
              // 存储样式对象
              // 有配置图标或者标签的话需要对表格列做个性化渲染
              // this.getTableColumns.forEach((i) => {
              //   if (i.field === column.field && i._type === 'field') {
              //     !i.slots && (i.slots = {})
              //     i.slots.default = ({ row, column }) => {
              //       const colorObj = this.cellCustomStyle[`${column.field}_${row[column.field]}`] || {}
              //       const tagStyle = {
              //         type: colorObj.tagType,
              //       }
              //       const iconStyle = {
              //         style: { color: colorObj.iconColor },
              //       }
              //       if (config.icon && config.tagContent) {
              //         return [
              //           <p>
              //             <vui-icon icon={color.icon} {...iconStyle} />
              //             <el-tag {...tagStyle}>{color.tagContent}</el-tag>
              //             <span>{row[column.field]}</span>
              //           </p>,
              //         ]
              //       } else if (config.icon) {
              //         return [
              //           <p>
              //             <vui-icon icon={colorObj.icon} {...iconStyle} />
              //             <span>{row[column.field]}</span>
              //           </p>,
              //         ]
              //       } else if (config.tagContent) {
              //         return [
              //           <p>
              //             <el-tag {...tagStyle}>{colorObj.tagContent}</el-tag>
              //             <span>{row[column.field]}</span>
              //           </p>,
              //         ]
              //       } else {
              //         return [
              //           <p>
              //             <span>{row[column.field]}</span>
              //           </p>,
              //         ]
              //       }
              //     }
              //   }
              // })
            }
          }
          // })
        })
        return color || {}
      },
      // 标签列样式
      tagCellStyle({ row, column }) {
        if (this.getCellStatusConfig && this.getCellStatusConfig.length > 0) {
          let color = {}
          this.getCellStatusConfig.forEach((v) => {
            if (column.field === v.key && row[v.key] !== undefined && row[v.key] === v.value) {
              color = {
                backgroundColor: v.color,
                color: v.textColor == undefined ? '#000000' : v.textColor,
                borderColor: v.borderColor || '',
              }
            }
          })
          if (!isEmpty(color)) {
            return color
          }
        }
        if (this.getColumnStatusConfig && this.getColumnStatusConfig.length > 0) {
          let color = this.calculateColumnColor({ row, column })
          if (!isEmpty(color)) {
            return color
          }
        }
      },
      //表格选中变化统一方法
      onTableSelectChang() {
        this.runEventTask('onTableSelectChang', {
          tableId: this.info._id,
          data: this.getCheckboxOrRadioVals(),
        })
      },
      //多选触发
      checkboxChange(data) {
        this.onTableSelectChang()

        this.clickRowId = data.checked ? data.rowid : ''
        this.hasCheckboxSelectAll = this.getTableRef().isAllCheckboxChecked()
        //特定时间触发
        this.emitEvents()
      },
      // 单选触发
      radioChange() {
        // 触发选中状态改变
        this.onTableSelectChang()
      },
      // page修改
      pageChange(e) {
        let { currentPage, pageSize } = e
        if (this.pageSize != pageSize) {
          currentPage = 1
        }
        //页面修改 初始化到1页
        this.setFormData(currentPage, pageSize)
        //请求
        this.request(
          {
            api: this.getInfo.extension.api.value,
            data: this.getInfo.data.formData,
            method: this.getInfo.extension.method.value,
          },
          function () {
            //没有需要选中的数据不执行
            if (!this.selectRow.row) {
              return
            }
            //触发选中
            this.setCheckboxRow(this.selectRow.row, this.selectRow.checked, this.selectRow.init)
          }
        )
      },
      //排序修改
      sortChange(data) {
        this.sortType[data.property] = data.order
      },
      // 统一请求
      request(options = {}, callback) {
        if (isEmpty(options.api) || isEmpty(options.method)) {
          this.$baseMessage('请填写表格Api 或者 Method')
          return
        }
        this.loading = true
        let getDataKey = this.getExtension.getDataKey.value
        //使用自定义参数
        // console.log('请求数据 ----- 表格 ------  ', this.$getRequestData())
        let _data = options.data
        if (this.getInfo.type.indexOf('uiSelectLayerNew') === -1) {
          // 如果不是 选择新 组件触发的 则进行数据处理
          _data = { ...options.data, ...this.$getRequestData() }
        }
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(_data),
            method: options.method,
          },
        })
          .then((res) => {
            this.loading = false
            //解密
            // console.log(decryptd(res))
            this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : isArray(res.data) ? res.data[0] : res.data[getDataKey]
            //添加回调
            callback && callback.call(this)
          })
          .catch(() => {
            this.loading = false
            this.getInfo.data.requestData = []
            //添加回调
            callback && callback.call(this)
          })
      },
      //右键菜单 条件处理
      cellMenuEvent({ row, options }) {
        if (options.length > 0) {
          let _menus = cloneDeep((this.info.extension.menuConfig && this.info.extension.menuConfig.value) || [])

          // 不显示模式
          // options[0] = _menus.filter((v) => {
          //   return this.handleStatusConfig(row, v)
          // })

          // console.log('bbfpl ', _menus, row)
          const handleChildren = (r, v, disabled) => {
            // if (v.name == '生成盘点任务') {
            //   console.log('bbfpl 1', r, v, disabled)
            // }

            if (v.children && v.children.length > 0) {
              v.children.forEach((vv) => {
                if (disabled) {
                  vv.disabled = true
                } else {
                  vv.disabled = this.handleStatusConfig(r, vv)
                  // 读取来自事件动作的属性
                  if (vv.disabledByAction) vv.disabled = true
                }
                handleChildren(r, vv, disabled)
              })
            }
          }
          // 禁用模式
          this.cellMenuList = []
          options[0] = _menus.map((v) => {
            v.disabled = this.handleStatusConfig(row, v)
            // 读取来自事件动作的属性
            if (v.disabledByAction) v.disabled = true
            handleChildren(row, v, v.disabled)
            return v
          })
        }
      },
      // 右键事件 { menu, row, column }
      contextMenuClickEvent({ menu, type, row, rowIndex, column, columnIndex }) {
        // 防抖
        if (this.menuClickIsRunning) return
        if (!this.getHasPreview) {
          return
        }
        // console.log('点击菜单', this, this.info, menu.code, {
        //   type,
        //   row,
        //   rowIndex,
        //   columnIndex,
        //   column,
        //   tableFun: {
        //     getTableColumns: cloneDeep(this.$getTableColumns()),
        //   },
        // })
        if (menu.code.length > 0) {
          if (row['#SEQ#']) {
            row['#SEQ#'] = columnIndex
          }

          //先给选择行打勾
          if (!this.menuClickIsRunning) {
            setTimeout(() => {
              actionsTask(
                this,
                this.info,
                menu.code,
                {
                  type,
                  row,
                  rowIndex,
                  columnIndex,
                  column,
                  tableFun: {
                    getTableColumns: cloneDeep(this.$getTableColumns()),
                  },
                },
                () => {
                  console.log('右键事件 完成了')
                },
                'menuClick'
              )
            })
          }
          // 事件动作节流 动作队列开始执行，则将执行状态改为true
          this.menuClickIsRunning = true
          setTimeout(() => {
            this.menuClickIsRunning = false
          }, 60000)
        } else {
          console.log('未配置交互')
        }
      },
      setRadioCheckboxRow(data) {
        if (this.hasCheckboxOrRadio == 'radio') {
          this.getTableRef().setRadioRow(data.row)
          this.emitEvents([data.row])
        }
        if (this.hasCheckboxOrRadio == 'checkbox') {
          //双击先清空选择 再打勾
          this.getTableRef().clearCheckboxRow()

          this.getTableRef().toggleCheckboxRow(data.row)
        }
      },
      getCheckboxOrRadioVals() {
        let _value = []
        if (this.hasCheckboxOrRadio == 'checkbox') {
          _value = this.getTableRef().getCheckboxRecords()
        } else {
          let v = this.getTableRef().getRadioRecord()
          _value = [v]
        }
        //特定组件触发
        this.emitEvents(_value)
        return _value
      },
      // 点击行选择 data
      cellClickEvent(data) {
        if (data.column && data.column.title == '操作') {
          console.log('点击操作区域不执行单行事件')
          return
        }
        // 点击选择列也不触发事件
        if (data.column && (data.column.type === 'checkbox' || data.column.type === 'seq')) return

        if (this.hasOpenEdit) {
          console.log('编辑模式下单击事件取消执行')
          // 关闭横向虚拟滚动 防止组件被重复渲染与销毁
          // 判断当前点击行与当前编辑行是否一样 一样则不做处理
          // const currentEditIndex =
          //   this.$refs[this.info._id].getEditRecord && this.$refs[this.info._id].getEditRecord() && this.$refs[this.info._id].getEditRecord().rowIndex
          // if (currentEditIndex === data.rowIndex) return
          // // 先清空上一次编辑模式下的编辑单元列表
          // this.$store.dispatch('tableFormItem/clearTableFormItemList')
          // this.$refs[this.info._id].setEditRow && this.$refs[this.info._id].setEditRow(data.row)
          // // 自动聚焦第一个可编辑单元
          // setTimeout(() => {
          //   const moduleList = this.$store.getters['tableFormItem/getTableFormItemList']
          //   if (moduleList[0] && moduleList[0].ref) {
          //     moduleList[0].ref.focus()
          //     moduleList[0].ref.select && moduleList[0].ref.select()
          //   }
          // })
          // return
        }

        if (this.hasCheckboxOrRadio !== 'checkbox') {
          this.setRadioCheckboxRow(data)
        }
        if (!this.hasPreview) {
          console.log('预览模式不运行 onDbClick')
          return
        }
        // 将匹配行标记单选状态
        this.$refs[this.info._id].setCurrentRow(data.row)
        this.runEventTask('onTableClick', {
          tableId: this.info._id,
          data: [data.row],
        })
      },
      // 双击打开图层
      cellDBLClickEvent(data) {
        if (data.column && (data.column.title == '操作' || data.column.type === 'expand')) {
          console.log('点击操作区域不执行双行事件')
          return
        }
        // 点击选择列也不触发事件
        if (data.column && (data.column.type === 'checkbox' || data.column.type === 'seq')) return

        this.setRadioCheckboxRow(data)
        if (!this.hasPreview) {
          console.log('预览模式不运行 onDbClick')
          return
        }
        if (this.hasOpenEdit) {
          // console.log(this.getTableRef().getEditRecord(), data, this.getTableRef().getEditRecord()?.rowIndex, data.rowIndex)
          // 如果当前表格开启了可编辑，则进入编辑模式
          if (this.getTableRef().getEditRecord() && this.getTableRef().getEditRecord().rowIndex === data.rowIndex) {
            // 如果之前已经是编辑状态并且当前点击的是之前的编辑行 则退出编辑模式
            this.quitEditModel()
            return
          }
          this.enterEditModel()
          return
        }

        this.onTableSelectChang()

        this.runEventTask('onTableDblClick', {
          tableId: this.info._id,
          data: this.getCheckboxOrRadioVals(),
        })
      },
      //表头拖动
      columnDrop() {
        this.$nextTick(() => {
          const $table = this.$refs[this.info._id]
          this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
            handle: '.vxe-header--column:not(.col--fixed)',
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn()
              const targetThElem = item // 要移动的列（真实DOM）
              const wrapperElem = targetThElem.parentNode // 所有的列（真实DOM）
              const newColumn = fullColumn[newIndex] // 目标位置现有的列（虚拟DOM）
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(targetThElem, wrapperElem.children[oldIndex])
                } else {
                  wrapperElem.insertBefore(wrapperElem.children[oldIndex], targetThElem)
                }
                return this.$baseMessage('固定列不允许拖动！')
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(tableColumn[oldIndex])
              const newColumnIndex = $table.getColumnIndex(tableColumn[newIndex])
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
              fullColumn.splice(newColumnIndex, 0, currRow)
              $table.loadColumn(fullColumn)
            },
          })
        })
      },
      onRefresh(callback) {
        this.hasClickRefreshLoading = true
        if (this.getKeppSelect) this.saveSelectedRows()
        this.$refreshTable().then(() => {
          if (isFunction(callback)) callback(this)
          this.hasClickRefreshLoading = false
          if (this.getKeppSelect) this.setkeepSelectData()
        })
      },
      //全选
      checkboxSelectAll() {
        this.onTableSelectChang()
        if (this.hasCheckboxSelectAll) {
          this.getTableRef().clearCheckboxRow(true)
        } else {
          this.getTableRef().setAllCheckboxRow(true)
        }
        this.hasCheckboxSelectAll = !this.hasCheckboxSelectAll
        //特定组件触发
        this.emitEvents()
      },
      //反选
      checkboxReverseSelection() {
        this.onTableSelectChang()
        const _table = this.getTableRef()
        //先获取当前选择
        const selectRecords = cloneDeep(_table.getCheckboxRecords())
        const allData = cloneDeep(_table.getData())
        console.log('allData', allData)

        let selectRecordsIds = []
        selectRecords.forEach((v) => {
          selectRecordsIds.push(v._X_ID)
        })
        let allDataIds = []
        allData.forEach((v) => {
          allDataIds.push(v._X_ID)
        })

        let arr = selectRecords.concat(allData)
        let result = arr.filter(function (v) {
          return selectRecordsIds.indexOf(v._X_ID) === -1 || allDataIds.indexOf(v._X_ID) === -1
        })
        //先清空当前选择 反选剩余的
        _table.clearCheckboxRow()
        _table.setCheckboxRow(result, true)
        //反射数据
        this.emitEvents(result)
      },
      //选中行
      setCheckboxRow(row, checked, init) {
        this.selectRow = {
          row: row,
          checked: checked,
          init: init,
        }
        //初始化执行
        if (init) {
          const getData = this.getData,
            result = []
          if (!getData) return
          for (let i = 0; i < row.length; i++) {
            for (let key in row[i]) {
              result.push(
                ...getData.filter((item) => {
                  return item[key] === row[i][key]
                })
              )
            }
          }
          row = result
        }
        //判断是单选还是复选
        if (this.hasCheckboxOrRadio === 'checkbox') {
          this.getTableRef().setCheckboxRow(row, checked)
        } else {
          this.getTableRef().setRadioRow(row[0])
        }
      },
      editActivedEvent({ row }) {
        this.cacheEditRows[row._X_ROW_KEY] = cloneDeep(row)

        if (isArray(this.getEditDefault)) {
          this.getEditDefault.forEach((v) => {
            row[v.key] = v.value //假设是默认值
          })
        }

        // this.editActivedVisible = true
      },
      async editClosedEvent({ column, row }) {
        // let oldRow = this.cacheEditRows[row._X_ROW_KEY]
        const $table = this.getTableRef()
        // 取消验证 防止验证开启时导致无法退出编辑模式
        // const errMap = await $table.fullValidate()
        const errMap = false
        //判断默认值是否被修改
        // 暂时取消回退原始值
        // const updateRecords = $table.getUpdateRecords()
        // if (updateRecords) {
        //   if (isArray(this.getEditDefault)) {
        //     this.getEditDefault.forEach((v) => {
        //       if (row[v.key] == v.value) {
        //         //说明没修改过默认值 恢复原始值
        //         // row[v.key] = oldRow[v.key]
        //       }
        //     })
        //   }
        // }
        if (errMap) {
          //校验未通过
          const msgList = []
          Object.values(errMap).forEach((errList) => {
            errList.forEach((params) => {
              const { rowIndex, column, rules } = params
              rules.forEach((rule) => {
                msgList.push(`第 ${rowIndex + 1} 行 ${column.title} 校验错误：${rule.message}`)
              })
            })
          })
          let msgHtml = ``
          msgList.forEach((msg) => {
            msgHtml += `${msg}<br>`
          })
          // this.$baseMessage(msgHtml, 'warning', '', true)
          console.log(msgHtml)
          return
        }

        // 如果不保存编辑数据则需要回退数据
        if (this.isNotSaveData) {
          $table.revertData(row)
          // 如果是新增表格数据进入 则需要重置事件状态
          if (this.isAddTableEdit) this.addTableDataEventObj.vm[`${this.addTableDataEventObj.eventName}IsRunning`] = false
          return
        }

        let _clickEdit = this.getInfo.extension.clickEdit.value
        // 如果是新增表格数据动作进入的编辑模式 则需要使用动作配置的接口
        if (this.isAddTableEdit && !this.addTableDataEventObj.saveApiConfig.api) {
          console.log('没配置api将不会自动提交')
          // 如果是新增表格数据进入 则需要重置事件状态
          this.addTableDataEventObj.vm[`${this.addTableDataEventObj.eventName}IsRunning`] = false
          return
        } else if (!this.isAddTableEdit && isEmpty(_clickEdit.method)) {
          console.log('没配置api将不会自动提交')
          return
        }

        const field = column.property
        const cellValue = row[field]
        // 判断单元格值是否被修改
        // 取消字段判断 防止行编辑最后一个单元格没有改变时不提交数据问题
        if ($table.isUpdateByRow(row) || this.isAddTableEdit) {
          // 组织新增表格数据接口的自定义参数
          const customParams = {}
          if (this.isAddTableEdit && this.addTableDataEventObj.saveApiConfig.requestData) {
            this.addTableDataEventObj.saveApiConfig.requestData.forEach((item) => {
              let itemVal = item.value
              if (/#{.*?}/g.test(item.value)) {
                itemVal = replaseRegVariable(itemVal, { ...row, ...this.info.data.formData })
              }
              customParams[item.key] = processingConstant(this, itemVal)
            })
          }

          const params = {
            url: GFCD('dams', 'domain') + (this.isAddTableEdit ? this.addTableDataEventObj.saveApiConfig.api : this.getInfo.extension.api.value),
            method: 'post',
            data: {
              data: JSON.stringify({
                ...row,
                ...customParams,
                '#LIMIT#': '1',
                '#PAGE_SIZE#': '50',
              }),
              method: this.isAddTableEdit ? this.addTableDataEventObj.saveApiConfig.method : _clickEdit.method,
            },
          }

          await request(params)
            .then((res) => {
              return new Promise((resolve, reject) => {
                if (_clickEdit.tipOpen && !this.isAddTableEdit) {
                  this.$baseMessage(`局部保存成功！ ${column.title}=${cellValue}`, 'success')
                }
                $table.reloadRow(row, null, field)
                if (this.isAddTableEdit && this.addTableDataEventObj.done) this.addTableDataEventObj.done(null, res)
                // 如果有配置编辑保存事件则先执行编辑保存动作
                if (!this.isAddTableEdit && this.info.extension.clickEdit.value.actions && this.info.extension.clickEdit.value.actions.length) {
                  actionsTask(
                    this,
                    this.info,
                    this.info.extension.clickEdit.value.actions,
                    {
                      tableId: this.info._id,
                      data: [row],
                    },
                    () => {
                      console.log('表格编辑事件 完成了')
                      resolve()
                    },
                    'editEvent',
                    res
                  )
                }
              })
            })
            .catch((error) => {
              return new Promise((resolve, reject) => {
                if (this.isAddTableEdit && this.addTableDataEventObj.done) this.addTableDataEventObj.done(null, error)
                // 如果有配置编辑保存事件则先执行编辑保存动作
                if (!this.isAddTableEdit && this.info.extension.clickEdit.value.actions && this.info.extension.clickEdit.value.actions.length) {
                  actionsTask(
                    this,
                    this.info,
                    this.info.extension.clickEdit.value.actions,
                    {
                      tableId: this.info._id,
                      data: [row],
                    },
                    () => {
                      console.log('表格编辑事件 完成了')
                      resolve()
                    },
                    'editEvent',
                    res
                  )
                }
              })
            })
        }
      },
      //反射事件
      emitEvents(result) {
        if (this.getInfo.type.indexOf('uiSelectLayerNew') !== -1) {
          let _value = result || []
          if (!result) {
            if (this.hasCheckboxOrRadio == 'checkbox') {
              _value = this.getTableRef().getCheckboxRecords()
            } else {
              let v = this.getTableRef().getRadioRecord()
              _value = [v]
            }
          }
          this.$emit('outSelected', {
            hasCheckboxOrRadio: this.hasCheckboxOrRadio,
            rows: _value,
          })
        }
      },
      //取消选中
      clearSelect() {
        if (this.hasCheckboxOrRadio === 'checkbox') {
          this.getTableRef().clearCheckboxRow()
        } else {
          this.getTableRef().clearRadioRow()
        }
      },
      //按钮操作
      operateClick(v, row) {
        if (v.code.length > 0) {
          //先给选择行打勾
          this.setRadioCheckboxRow({ row: row })
          actionsTask(
            this,
            this.info,
            v.code,
            {
              tableId: this.info._id,
              data: [row],
            },
            () => {
              console.log('操作按钮事件 完成了')
            }
          )
        } else {
          console.log('未配置交互')
        }
      },
      //处理常量
      processConstant(obj = {}) {
        for (let key in obj) {
          obj[key] = processingConstant(this, obj[key])
        }
      },
      //批次属性初始化
      batchAttributeInit() {
        if (!this.getHasPreview) {
          return
        }
        if (this.getInfo.extension.batchAttribute && this.getInfo.extension.batchAttribute.value.open) {
          //动态表头获取模式下 不展示拖拉拽自定义
          this.isShowCustom = false
          this.request(
            {
              api: this.getInfo.extension.api.value,
              data: this.getInfo.data.formData,
              method: this.getInfo.extension.method.value,
            },
            () => {
              let list = this.getInfo.data.requestData.data
              let tableColumns = []
              let _columns = {}
              if (list.length > 0) {
                _columns = list[0]
                for (let key in _columns) {
                  if (key.slice(0, 1) != '#' && key.slice(key.length - 1) != '#') {
                    tableColumns.push({
                      _id: `field_${key}`,
                      _type: 'field',
                      field: key,
                      title: key,
                      sortable: true,
                      fixed: '',
                      width: '150',
                      openEdit: false,
                      openSearch: false,
                      minWidth: '100px',
                      showHeaderOverflow: true,
                      id: `field_${key}`,
                      label: key,
                      children: [],
                      isChecked: false,
                      searchConfig: {},
                    })
                  }
                }
                this.batchAttributeColumns = tableColumns
              }
            }
          )
          // let batchAttribute = this.getInfo.extension.batchAttribute
          // if (isEmpty(batchAttribute.value.api) || isEmpty(batchAttribute.value.method)) {
          //   console.log('请先配置批次api')
          //   return
          // }
          // let _data = { '#LIMIT#': 1, '#PAGE_SIZE#': 100 }
          // batchAttribute.value.data.forEach((v) => {
          //   _data[v.key] = processingConstant(this, v.value)
          // })
          // console.log('_data', _data)
          // //请求
          // request({
          //   url: GFCD('dams', 'domain') + batchAttribute.value.api,
          //   method: 'post',
          //   data: {
          //     data: JSON.stringify(_data),
          //     method: batchAttribute.value.method,
          //   },
          // }).then((res) => {
          //   let list = res.data[batchAttribute.value.method].data
          //   let tableColumns = []
          //   list.forEach((v) => {
          //     tableColumns.push({
          //       _id: `field_${v['#TABLE_KEY#']}`,
          //       _type: 'field',
          //       field: v['#TABLE_KEY#'],
          //       title: v['#TABLE_LABEL#'],
          //       sortable: true,
          //       fixed: '',
          //       width: '150',
          //       openEdit: false,
          //       openSearch: false,
          //       minWidth: '100px',
          //       showHeaderOverflow: true,
          //       id: `field_${v['#TABLE_KEY#']}`,
          //       label: v.title,
          //       children: [],
          //       isChecked: false,
          //       searchConfig: {},
          //     })
          //   })
          //   this.batchAttributeColumns = tableColumns
          // })
        }
      },
      //获取自定义请求参数
      $getRequestData() {
        let _data = {}
        if (this.getExtension.requestData && isArray(this.getExtension.requestData.value)) {
          this.getExtension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/{[^#{]+}/g.test(item.value)) {
              // const dataKey = trim(item.value.substring(2, item.value.length - 1))
              // 如果在formData中查询不到值 则查询数据源缓存值
              // itemVal = this.info.data.formData[dataKey] === undefined ? this.dataSourceFormData[dataKey] : this.info.data.formData[dataKey]
              itemVal = replaseRegVariable(itemVal, { ...this.dataSourceFormData, ...this.info.data.formData })
            }
            _data[item.key] = processingConstant(this, itemVal)
          })
        }
        return _data
      },
      // 刷新表格
      $refreshTable(notResetPage) {
        if (this.editModel && this.isAddTableEdit) {
          // 如果是新增表格数据进入 则需要重置事件状态(兼容点击新增之后直接刷新表格数据，下次无法点击新增问题)
          this.addTableDataEventObj.vm[`${this.addTableDataEventObj.eventName}IsRunning`] = false
        }
        !notResetPage && this.setFormData(1, this.pageSize)
        if (this.getInfo.extension.batchAttribute && this.getInfo.extension.batchAttribute.value.open) {
          // 如果开启了动态表头 则调用动态表头方法
          this.batchAttributeInit()
          return
        }
        let options = {
          api: this.getInfo.extension.api.value,
          data: this.getInfo.data.formData,
          method: this.getInfo.extension.method.value,
        }
        //添加参数(取消选择新组件的数据合格，已在组件自生完成合并)
        // if (this.getInfo.type.indexOf('uiSelectLayerNew') !== -1) {
        //   let requestDataObj = {}
        //   isArray(this.info.extension.requestData.value) &&
        //     this.info.extension.requestData.value.forEach((item) => {
        //       requestDataObj[item.key] = item.value
        //     })
        //   this.processConstant(requestDataObj)
        //   options = {
        //     api: this.info.extension.api.value,
        //     method: this.info.extension.method.value,
        //     getDataKey: this.info.extension.getDataKey.value,
        //     data: merge(this.info.data.formData, requestDataObj),
        //   }
        // }
        //请求
        return this.request(options)
      },
      // 重置表格
      $resetTable() {
        this.setFormData(1, this.pageSize)
        //请求
        return this.request({
          api: this.getInfo.extension.api.value,
          data: this.cacheFormData,
          method: this.getInfo.extension.method.value,
        })
      },
      //获取当前页面
      $getCurrentPage() {
        return this.currentPage
      },
      //获取排序状态
      $getSortType() {
        return this.sortType
      },
      //获取表头
      $getTableColumns() {
        return this.getTableColumns
      },
      $getCheckboxOrRadioVals() {
        let list = cloneDeep(this.getCheckboxOrRadioVals())
        list.forEach((v) => {
          v['#SEQ#'] = this.getTableRef().getRowIndex(v) + 1
        })
        return list
      },
      $getAllData() {
        const _table = this.getTableRef()
        let list = cloneDeep(_table.getData())
        list.forEach((v) => {
          v['#SEQ#'] = _table.getRowIndex(v) + 1
        })
        return list
      },
    },
  })
</script>
<style lang="scss">
  @import './style.scss';
  .vxe-table--context-menu-wrapper {
    &.notAllowed {
      ul li a {
        cursor: not-allowed;
      }
    }
  }
</style>
<style lang="scss" scoped>
  .noScrollBar {
    &::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
    .vxe-table--body-wrapper::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
  }
  .cunstomTableStyle {
    .vxe-table--render-default .vxe-table--empty-content {
      transform: scale(0.5);
    }
    .vxe-table--header-wrapper,
    .vxe-header--row,
    .vxe-table--body-wrapper,
    .vxe-table--render-default.border--default .vxe-table--header-wrapper,
    .vxe-table--render-default.border--full .vxe-table--header-wrapper,
    .vxe-table--render-default.border--outer .vxe-table--header-wrapper,
    .vxe-pager,
    .vxe-pager .vxe-pager--jump-next,
    .vxe-pager .vxe-pager--jump-prev,
    .vxe-pager .vxe-pager--next-btn,
    .vxe-pager .vxe-pager--num-btn,
    .vxe-pager .vxe-pager--prev-btn,
    .vxe-pager .vxe-pager--jump .vxe-pager--goto,
    .vxe-input--inner,
    .vxe-loading,
    .vxe-loading--chunk,
    .vxe-loading--text,
    .vxe-header--row .vxe-cell--title,
    .vxe-table--header,
    colgroup,
    colgroup col,
    .vxe-table--render-default .vxe-body--row.row--current,
    .row--current,
    .vxe-table--render-default .vxe-body--row.row--hover.row--current,
    .row--stripe,
    .vxe-grid.is--loading:before,
    .vxe-table--render-default .vxe-body--row.row--stripe {
      background-color: inherit;
      color: inherit;
      border-color: inherit;
    }
    .vxe-table--render-default .vxe-body--row.row--hover,
    .vxe-table--render-default .vxe-body--row.row--hover.row--stripe {
      background-color: #f5f7fa59;
    }
    .vxe-table--render-default,
    .vxe-table--render-wrapper,
    .vxe-table--main-wrapper,
    .vxe-table--header-border-line,
    .vxe-cell,
    .vxe-header--column,
    thead,
    .vxe-resizable,
    .vxe-pager--jump-prev,
    .vxe-pager--wrapper,
    .vxe-grid--pager-wrapper,
    .vxe-table--render-default .vxe-table--footer-wrapper,
    vxe-table--render-default.border--default .vxe-table--header-wrapper,
    .vxe-table--render-default.border--full .vxe-table--header-wrapper,
    .vxe-table--render-default.border--outer .vxe-table--header-wrapper,
    .vxe-table--render-default.border--default .vxe-body--column,
    .vxe-table--render-default.border--default .vxe-footer--column,
    .vxe-table--render-default.border--default .vxe-header--column,
    .vxe-table--render-default.border--inner .vxe-body--column,
    .vxe-table--render-default.border--inner .vxe-footer--column,
    .vxe-table--render-default.border--inner .vxe-header--column,
    .vxe-table--render-default.border--full .vxe-body--column,
    .vxe-table--render-default.border--full .vxe-footer--column,
    .vxe-table--render-default.border--full .vxe-header--column,
    .vxe-table--render-default.border--default .vxe-table--header-wrapper .vxe-header--row:last-child .vxe-header--gutter,
    .vxe-table--render-default.border--full .vxe-table--header-wrapper .vxe-header--row:last-child .vxe-header--gutter,
    .vxe-table--render-default.border--inner .vxe-table--header-wrapper .vxe-header--row:last-child .vxe-header--gutter,
    .vxe-table--render-default.border--outer .vxe-table--header-wrapper .vxe-header--row:last-child .vxe-header--gutter,
    .vxe-table--render-default .vxe-table--border-line,
    .vxe-table--render-default .vxe-body--expanded-column,
    .vxe-table .vxe-table--header-wrapper .vxe-table--header-border-line,
    .vxe-export--panel .vxe-export--panel-column .vxe-export--panel-column-header,
    .vxe-toolbar.is--perfect,
    .vxe-toolbar .vxe-custom--option-wrapper,
    .vxe-pager--jump,
    .vxe-pager--btn-icon,
    .vxe-pager--jump-icon,
    .vxe-input--inner,
    .vxe-select > .vxe-input .vxe-input--inner,
    .vxe-input,
    .vxe-select {
      border-color: inherit;
      background-image: inherit;
    }
    .vxe-table--render-default.border--full .vxe-body--column,
    .vxe-table--render-default.border--full .vxe-footer--column,
    .vxe-table--render-default.border--full .vxe-header--column {
      background-image: inherit;
    }
    .is--disabled .vxe-icon--d-arrow-left::after,
    .is--disabled .vxe-icon--d-arrow-left::before,
    .is--disabled .vxe-icon--d-arrow-right::after,
    .is--disabled .vxe-icon--d-arrow-right::before {
      border-left-color: inherit;
      border-top-color: inherit;
    }
    .is--disabled .vxe-icon--arrow-bottom::before,
    .is--disabled .vxe-icon--arrow-left::before {
      border-right-color: inherit;
      border-top-color: inherit;
    }
    .vxe-icon--caret-bottom:before {
      border-top-color: inherit;
    }
    .is--disabled .vxe-icon--arrow-right::before,
    .is--disabled .vxe-icon--arrow-top::before {
      border-right-color: inherit;
      border-top-color: inherit;
    }
    .vxe-table--render-default,
    .vxe-icon-spinner ::before,
    .vxe-select {
      color: inherit;
    }
  }

  // 重置进度条样式
  :deep() {
    .el-progress .el-progress-bar .el-progress-bar__inner {
      text-align: left;
    }
  }
</style>
